package loc.dd.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import loc.dd.entity.Pend;
import loc.dd.entity.Project;
import loc.dd.entity.User;
import loc.dd.service.ProjectService;
import loc.dd.service.UserService;
import net.sf.json.JSONObject;

/**
*@author 作者：huyaqi
*@version 创作时间:2023年11月28日下午3:34:18
*
*/
@RestController
@RequestMapping("/project")
public class ProjectController {
	private static Logger logger =LoggerFactory.getLogger(ProjectController.class);
	
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserService userservice;
	
    @Value("${file.upload.dir}")
    private String fileUploadDir;
    
    @Value("${file.download.dir}")
    private String fileUploadPath;
    
/**
 * 展示所有项目	
 * @param params
 * @param request
 * @param response
 * @return
 */
    @CrossOrigin
	@RequestMapping(value = "show" , method = RequestMethod.GET)
	public JSONArray show(HttpServletRequest request,HttpServletResponse response) {
		JSONArray jo = new JSONArray();
		String pageSize = request.getParameter("pageSize");
		String page = request.getParameter("page");
		String uid = request.getParameter("uid");
		System.out.println("show");
		int a = 0;
		int b = 10000;
		if(null != page && !"".equals(page)) {
			if(null != pageSize && !"".equals(pageSize)) {
				a = Integer.parseInt(page);
				b = Integer.parseInt(pageSize);
				if(a==1) {
					a=0;
				}else {
				 a=b*(a-1);
				}
			}
		}
		List<Map<String, Object>> projects= new ArrayList<Map<String, Object>>();
		String qxid =  userservice.getqx(uid);//获取权限，4为政企只能查看自己提交的
		int sum = 0 ;
		if(!"4".equals(qxid) && qxid !=null) {
			String aid = userservice.getAid(uid);
			List<String> aidList = Arrays.asList(aid.split(","));
			projects = projectService.getallmessage(a,b,aidList);
			//int sum = projectService.getsum();
			System.out.println(projects);
			sum =projects.size();
			System.out.println(sum);
			}else {
			projects = projectService.getzqmessage(a,b,uid);
			System.out.println(projects);
			sum =projects.size();
			System.out.println(sum);
		}
		jo.add(projects);	
		jo.add(sum);
		return jo;
	}
	
	
	/**
	 * 新增项目
	 * @param params
	 * @param request
	 * @param response
	 * @return
	 */
    @CrossOrigin
	@RequestMapping(value = "add" , method = RequestMethod.POST)
	public Map<String,Object> login(@RequestBody JSONObject params,HttpServletRequest request,HttpServletResponse response) {
		JSONObject jsonx = (JSONObject) params.get("data");
		Map<String, Object> map = new HashMap<>();
		Project project =new Project();
		System.out.println(jsonx);
		String orderName=(String)jsonx.get("orderName");
		String orderInfo=(String)jsonx.get("orderInfo");
		String orderTime=jsonx.get("orderTime").toString();
		net.sf.json.JSONArray orderAbility2 = jsonx.getJSONArray("orderAbility");
		String orderAbility = orderAbility2.toString().replaceAll("\"", "");
		orderAbility=orderAbility.replace("[", "").replace("]","");
		net.sf.json.JSONArray orderFiles2 = jsonx.getJSONArray("orderFiles");
		String orderFiles = orderFiles2.toString().replaceAll("\"", "");
		orderFiles=orderFiles.replace("[", "").replace("]","");
		System.out.println(orderFiles);
		String orderCreater=jsonx.get("orderCreater").toString();
//		String status=(String)jsonx.get("status");
		orderFiles = (orderFiles != null && !orderFiles.isEmpty()) ? orderFiles : "暂无附件";
		project.setOrderName(orderName);
		project.setOrderInfo(orderInfo);
		project.setOrderTime(orderTime);
		project.setOrderAbility(orderAbility);
		project.setOrderFiles(orderFiles);
		project.setOrderCreater(orderCreater);
		try {
			projectService.addproject(project);
			Map<String, Object> projects= new HashMap<String, Object>();
			projects = projectService.getmessage(project.getId());
			map.put("status", "200");
			map.put("project", projects);
			return map;
		}catch (Exception e) {
		    // 处理其他异常类型
		    e.printStackTrace(); // 或者进行其他处理
		    map.put("status", "407");
			return map;
		}
		}
	
	
	/**
	 * 模糊查找
	 * @param request
	 * @param response
	 * @return
	 */
    @CrossOrigin
	@RequestMapping(value = "select" , method = RequestMethod.GET)
	public JSONArray selectproject(HttpServletRequest request,HttpServletResponse response) {
		JSONArray jo = new JSONArray();
		String orderName = request.getParameter("orderName");
		List<Map<String, Object>> ab= new ArrayList<Map<String, Object>> ();
		String pageSize = request.getParameter("pageSize");
		String uid = request.getParameter("uid");
		String page = request.getParameter("page");
		int a = 0;
		int b = 10000;
		if(null != page && !"".equals(page)) {
			if(null != pageSize && !"".equals(pageSize)) {
				a = Integer.parseInt(page);
				b = Integer.parseInt(pageSize);
				if(a==1) {
					a=0;	
				}else {
				 a=b*(a-1);
				}
			}
		}
		String qxid =  userservice.getqx(uid);//获取权限，4为政企只能查看自己提交的
		int sum = 0 ;
		if(!"4".equals(qxid) && qxid !=null) {
			String aid = userservice.getAid(uid);
			List<String> aidList = Arrays.asList(aid.split(","));
			ab = projectService.selectproject(orderName,a,b,aidList);
			sum =ab.size();
			//int sum = projectService.selectsum(orderName);
			System.out.println(ab);
		}else {
			ab = projectService.selectzqproject(orderName,a,b,uid);
			System.out.println(ab);
			sum =ab.size();
			System.out.println(sum);
		}
		
		jo.add(ab);	
		jo.add(sum);
		System.out.println(sum);
		return jo;
    }
	
	/**
	 * 详情
	 * @param request
	 * @param response
	 * @return
	 */
    @CrossOrigin
	@RequestMapping(value = "detail" , method = RequestMethod.GET)
	public Map<String,Object> detail(HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> ab= new HashMap<String, Object> ();
		if(null != request.getParameter("pid") && !"".equals( request.getParameter("pid"))) {
			String id = request.getParameter("pid");
			ab = projectService.detail(Integer.valueOf(id));
			String orderFiles = (String) ab.get("orderFiles");
//			if(!"".equals(orderFiles) && orderFiles != null) {
//				 String[] fileArray = orderFiles.split(",");
//	                for (int i = 0; i < fileArray.length; i++) {
//	                    fileArray[i] = "172.16.0.202:8081/project/download/" + fileArray[i];
//	                }
//	                ab.put("orderFiles", fileArray);
//			}
			if (!"".equals(orderFiles) && orderFiles != null) {
			    String[] fileArray = orderFiles.split(",");
			    List<Map<String, String>> fileList = new ArrayList<>();
			    for (String fileName : fileArray) {
			        Map<String, String> fileMap = new HashMap<>();
//			        fileMap.put("fullPath", "172.16.0.202:8081/project/download/");
			        fileMap.put("fullPath", fileUploadPath);
			        
			        fileMap.put("name", fileName);
			        fileList.add(fileMap);
			    }
//			    System.out.println("fileList="+fileList);
			    ab.put("orderFiles", fileList);
			}
			List<Map<String, Object>> cd= new ArrayList<Map<String, Object>>();
		    cd = projectService.getprocess(Integer.valueOf(id));  
		    for (Map<String, Object> item : cd) {
		        String processFiles = (String) item.get("procesFiles");
		        if (!"".equals(processFiles) && processFiles != null) {
		            String[] fileArray = processFiles.split(",");
		            List<Map<String, String>> fileList = new ArrayList<>();
		            for (String fileName : fileArray) {
		                Map<String, String> fileMap = new HashMap<>();
//		                fileMap.put("fullPath", "172.16.0.202:8081/project/download/");
		                fileMap.put("fullPath", fileUploadPath);
		                fileMap.put("name", fileName);
		                fileList.add(fileMap);
		            }
		            // 替换原始的 processfile 字段
		            item.put("processfile", fileList);
//		            System.out.println("item="+item);
		        }
		    }
		    String status = (String) ab.get("status");
		    int statusAsInt = Integer.parseInt(status);
		    if (statusAsInt == 2) {
//		    	Pend pend2 = new Pend();
//		    	pend2 = projectService.getend(Integer.valueOf(id));
		    	Map<String, Object> pend= new HashMap<String, Object> ();
		    	pend = projectService.getend(Integer.valueOf(id));
//		    	pend.put("pend", pend2);
//		    	pend.put("status", status);
		    	System.out.println(pend);
		    	ab.put("pend", pend);
		    } else {
//		    	Pend pend = new Pend();
//		    	ab.put("pend", pend);
		    	ab.put("status", status);
		    }
		    ab.put("processList", cd);
		    System.out.println(ab);
			return ab;
		}
		else {
			ab.put("status", 407);
		}
		return ab;
    }
	
	/**
	 * 完结项目
	 * @param params
	 * @param request
	 * @param response
	 * @return
	 */
    	@CrossOrigin
		@RequestMapping(value = "finish" , method = RequestMethod.POST)
		public Map<String,Object> finish(@RequestBody JSONObject params,HttpServletRequest request,HttpServletResponse response) {
			JSONObject jsonx = (JSONObject) params.get("data");
			Map<String, Object> pend= new HashMap<String, Object> ();
			Pend pend1 =new Pend();
			System.out.println("jsonx ===== " + jsonx);
			String pid=jsonx.get("pid").toString();
			String xmnl = "";
			try {
				xmnl = projectService.gettjnl(pid); //总共有几个能力，对应几个进度
				int jdsl = projectService.gettjjd(pid); //总共有几个进度，与上面的对比
				String[] xmnl2 = xmnl.split(",");
		        // 获取数字的个数
		        int numberCount = xmnl2.length;
		        	if(numberCount > jdsl) {
		        		pend.put("status", "402");
		        		return pend;
		        	}
			}catch(Exception e) {
				e.printStackTrace();
			}
			String userid=jsonx.get("userid").toString();
			String confimTime=jsonx.get("confimTime").toString();
			String confimInfo=jsonx.get("confimInfo").toString();
			String username=jsonx.get("username").toString();
			pend1.setConfimInfo(confimInfo);
			pend1.setConfimTime(confimTime);
			pend1.setUserid(userid);
			pend1.setUsername(username);
			pend1.setPid(pid);
			try {
				projectService.endproject(pend1);
				projectService.updatestatus(2,Integer.valueOf(pid));
				pend.put("id", pend1.getId());
				pend.put("pid", pend1.getPid());
				pend.put("userid", pend1.getUserid());
				pend.put("confimTime", pend1.getConfimTime());
				pend.put("confimInfo", pend1.getConfimInfo());
				pend.put("username", pend1.getUsername());
				pend.put("status", "2");
				List<String> aidList = Arrays.asList(xmnl.split(","));
				List<Map<String, Object>> userlist= new ArrayList<Map<String, Object>>();
				userlist = userservice.getjifenrenyuan(aidList);//获取这个项目所有有能力得到积分的人员列表
				pend.put("userlist", userlist);
				System.out.println("jsonx ===== "+ pend);
				return pend;
			} catch (Exception e) {
				 e.printStackTrace();
			}
			pend.put("error","407");	
			return pend;
		}

    	
    	/**
    	 * 获取积分
    	 * @param params
    	 * @param request
    	 * @param response
    	 * @return
    	 * @throws JsonProcessingException 
    	 * @throws JsonMappingException 
    	 */
        @CrossOrigin
    	@RequestMapping(value = "getpoint" , method = RequestMethod.POST)
        public Map<String,Object> getpoint(@RequestBody JSONObject params,HttpServletRequest request,HttpServletResponse response) throws JsonMappingException, JsonProcessingException {
        	 ObjectMapper objectMapper = new ObjectMapper();
             // 将JSON字符串转换为JsonNode
             JsonNode jsonNode = objectMapper.readTree(params.toString());
             // 获取"data"节点下的数组
             JsonNode jsonx = jsonNode.get("data");
             String pid = jsonNode.get("pid").toString();
        	System.out.println("jsonx ===== " + jsonx);
        	System.out.println("pid ===== " + pid);
        	List<Map<String, Object>> resultList = new ArrayList<>();
            for (JsonNode entry : jsonx) {
                Map<String, Object> entryMap = objectMapper.convertValue(entry, Map.class);
                JsonNode jfNode = entry.get("jf");
                int jfValue = (jfNode != null && !jfNode.isNull()) ? jfNode.asInt() : 0;
                // 将 jf 字段添加到 entryMap 中
                entryMap.put("jf", jfValue);
                entryMap.put("pid", pid);
                resultList.add(entryMap);
            }
            List<Map<String, Object>> updateUserList = new ArrayList<>();
            for (Map<String, Object> entry : resultList) {
                // 获取 id 字段的值
                Object idValue = entry.get("id");
                int jfValue = (int) entry.get("jf");
                // 将 id 字段移除
                entry.remove("id");
                // 将 id 字段的值添加到 ids 字段
                entry.put("ids", idValue);
                Map<String, Object> updateUserMap = new HashMap<>();
                updateUserMap.put("id", entry.get("ids")); // ids字段对应user表的id
                updateUserMap.put("jf", jfValue); // 根据jf值判断是否加分
                updateUserList.add(updateUserMap);
            }
            System.out.println("转化结果 ===== " + resultList);
            Map<String, Object> status= new HashMap<String, Object> ();
            try {
            	projectService.inserjf(resultList); 
            	projectService.updateUserPoints(updateUserList);
     			status.put("status", 200);
     			status.put("zt", "成功");
			} catch (Exception e) {
				 e.printStackTrace();
	     		status.put("status", 407);
	     		status.put("zt", "失败");
			}
			return status; 
        	}

        
        
    	//首页
    	@CrossOrigin
		@RequestMapping(value = "index" , method = RequestMethod.GET)
		public Map<String,Object> index(HttpServletRequest request,HttpServletResponse response) {
			Map<String, Object> index= new HashMap<String, Object> ();
			List<Map<String, Object>> message= new ArrayList<Map<String, Object>>();
			String uid = request.getParameter("uid");
			int orderNum = 0;
			int orderProces = 0;
			int orderEnd = 0;
			List<Map<String, Object>> projects= new ArrayList<Map<String, Object>>();
			String qxid =  userservice.getqx(uid);//获取权限，4为政企只能查看自己提交的
			int sum = 0 ;
			String aid = userservice.getAid(uid);
			List<String> aidList = Arrays.asList(aid.split(","));
			if(!"4".equals(qxid) && qxid !=null) {
				orderNum = projectService.getorderNum(aidList).size();//该能力总工单数
				orderProces = projectService.getorderProces(aidList).size();//该能力工单进行数
				orderEnd = projectService.getorderEnd(aidList).size();//该能力总工单完成数
				message =projectService.getindexmessage(aidList);
			}else {
				orderNum = projectService.getorderNumzq(uid);//该能力总工单数
				orderProces = projectService.getorderProceszq(uid);//该能力工单进行数
				orderEnd = projectService.getorderEndzq(uid);//该能力总工单完成数
				message =projectService.getindexmessagezq(uid);
			}
			index.put("orderNum", orderNum);
			index.put("orderProces", orderProces);
			index.put("orderEnd", orderEnd);
			index.put("orderLists", message);
			System.out.println(index);
			return index;
		}
	
	
	
	
	/**
	 * 上传附件
	 * @param file
	 * @return
	 */
    @CrossOrigin
	@RequestMapping("/uploadFile")
	    public String handleFileUpload(@RequestParam("file") MultipartFile[] files) {
		 List<String> filePaths2 = new ArrayList<>();
		 String  filePaths = "";
		if (files == null || files.length == 0) {
			filePaths="文件为空";
			return filePaths;
        }
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
            	filePaths="文件为空";
    			return filePaths;
            }
            try {
                // 指定文件保存的目录
//            	String uploadDir = "E:/upload/";
            	String uploadDir = fileUploadDir;
                String fileName = file.getOriginalFilename();

                // 获取当前时间戳
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String timestamp = dateFormat.format(new Date());

                // 将时间戳添加到文件名中
                String baseName = fileName.substring(0, fileName.lastIndexOf('.'));
                String extension = fileName.substring(fileName.lastIndexOf('.'));
                fileName = baseName + "_" + timestamp + extension;

                // 创建目标文件
                File dest = new File(uploadDir + fileName);
                dest.createNewFile();

                // 将上传的文件保存到目标文件
                file.transferTo(dest);
                // 记录文件路径
//                filePaths.add(fileName);
                filePaths=fileName;
                System.out.println(filePaths);
                return filePaths;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return filePaths;
    }
	/**
	 * 下载附件  
	 * @param fileName
	 * @return
	 */
    @CrossOrigin
	 @GetMapping("/download/{fileName:.+}")
	    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
	        // 构建文件路径
//		 	String uploadDir = "E:/upload/";
//	        Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();
//	        Resource resource;
//
//	        try {
//	            // 尝试加载文件作为资源
//	            resource = new UrlResource(filePath.toUri());
//	        } catch (IOException e) {
//	            e.printStackTrace();
//	            // 处理文件加载异常
//	            return ResponseEntity.notFound().build();
//	        }
//	        // 构建下载响应
//	        return ResponseEntity.ok()
//	                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
//	                .body(resource);
//		 String uploadDir = "E:/upload/";
		 String uploadDir = fileUploadDir;
	        Path filePath = Paths.get(uploadDir).resolve(fileName).normalize();
	        Resource resource;

	        try {
	            // 尝试加载文件作为资源
	            resource = new UrlResource(filePath.toUri());
	        } catch (IOException e) {
	            e.printStackTrace();
	            // 处理文件加载异常
	            return ResponseEntity.notFound().build();
	        }

	        // 对文件名进行URL编码
	        String encodedFileName;
	        try {
	            encodedFileName = URLEncoder.encode(resource.getFilename(), "UTF-8");
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	            // 处理编码异常
	            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	        }

	        // 构建下载响应
	        return ResponseEntity.ok()
	                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"")
	                .contentType(MediaType.APPLICATION_OCTET_STREAM)
	                .body(resource);
	    
		 
	    }
	
}
